<?php

namespace app\common\controller;

class Course extends Common
{
    //获取课程列表，默认下发第1页的数据，每页10条数据
    public function getCourseList($param = [], $pageNo = 1, $pageLimit = 10)
    {
        $map = [];
        //支持筛选课程分类
        if (isset($param['classId'])) {
            $map['classId'] = $param['classId'];
        }

        //支持筛选老师
        if (isset($param['teacherId'])) {
            $map['teacherId'] = $param['teacherId'];
        }

        //支持筛选课程状态
        if (isset($param['status'])) {
            $map['status'] = $param['status'];
        }

        //支持模糊查询课程标题名称
        if (isset($param['title'])) {
            $map['title'] = ['like', '%' . $param['title'] . '%'];
        }

        //分页查询下发数据
        $ret = [];
        $ret['items'] = db('course')->where($map)->limit($pageLimit)->page($pageNo)->select();
        $ret['total'] = db('course')->where($map)->count();
        $ret['pageNo'] = $pageNo;
        return $ret;
    }

    //保存课程
    public function saveCourse($data)
    {
        if (empty($data)) {
            exception('参数错误');
        }
        
        $ret = false;

        //如果有id则为修改，否则就新增
        if (empty($data['id'])) {
            $ret = db('course')->insert($data);
        } else {
            $ret = db('course')->update($data);
        }

        return $ret;
    }

    //删除课程
    public function delCourse($id)
    {
        if (empty($id)) {
            exception('参数错误');
        }

        return db('course')->where('id', intval($id))->delete();
    }

    //课程批量上架或下架
    public function batchUpdateStatus($courseIds, $status)
    {
        if (empty($courseIds)) {
            exception('参数错误');
        }

        $map = [
            'id' => ['in', $courseIds],
        ];
        $data = [
            'status' => $status,
        ];
        return db('course')->where($map)->update($data);
    }
}
